<?php
/**
 * （Logic）每日库存统计(按公司SKU)（amazon每日库存记录）
 */

namespace App\Logic\Amazon\Statistics;

use App\Models\Amazon\DailyInventory;
use App\Models\Amazon\DailyInventorySR as ADailyInventorySR;
use Illuminate\Support\Facades\DB;
class DailyInventorySR
{
    /**
     * Amazon每日库存统计（公司SKU）
     * @param int $day
     */
    public static function init($day = 0){
        try{
            DB::beginTransaction();
            $date = date('Y-m-d',strtotime("-$day days"));
            $lines = DailyInventory::query()
                ->where('re_date',$date)
                ->where('psku_id','<>',0)
                ->selectRaw('country_id,psku_id,sum(quantity) as quantity')
                ->groupBy(['country_id','psku_id'])
                ->get();
            $i = 0;
            $num = 500;
            while(true){
                if($lines->isEmpty())break;
                $_lines = $lines->splice($i,$num);
                foreach ($_lines as $line){
                    ADailyInventorySR::query()->updateOrCreate(
                        [
                            're_date' => $date,
                            'country_id' => $line->country_id,
                            'psku_id' => $line->psku_id,
                        ],
                        [
                            'quantity' => $line->quantity,
                        ]
                    );
                }
                DB::commit();
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
